import { useSyncExternalStore } from 'react';

// 实现跳转 监听history变化
export const useHistory = () => {
    // 订阅者
    const subscribe = (callback: () => void) => {
        // 订阅浏览器api 监听路由的变化
        // vue的三种路由结构 ssr hash history
        // hash 监听hashchange 注意  只能监听浏览器的前进后退按钮
        // history 监听popstate 注意  只能监听浏览器的前进后退按钮
        // ssr 监听popstate
        window.addEventListener('hashchange', callback); //callback刷新视图
        window.addEventListener('popstate', callback);
        return () => {
            //取消订阅
            window.removeEventListener('storage', callback);
            window.removeEventListener('popstate', callback);
        };
    };

    const getSnapshot = () => {
        return window.location.href;
    };
    const url = useSyncExternalStore(subscribe, getSnapshot);
    const push = (url: string) => {
        window.history.pushState({}, '', url);
        window.dispatchEvent(new PopStateEvent('popstate')); //手动触发popstate事件
    };
    const replace = (url: string) => {
        window.history.replaceState({}, '', url);
        window.dispatchEvent(new PopStateEvent('popstate')); //手动触发popstate事件
    };
    return [url, push, replace] as const;
};
